package cn.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import cn.dao.CategoryDao;
import cn.dao.JDBCUtils;
import cn.dao.impl.CategoryDaoImpl;
import cn.dto.PageInfo;
import cn.pojo.Category;
import cn.service.CategoryService;

public class CategoryServiceImpl implements CategoryService{
	private CategoryDao categoryDao = new CategoryDaoImpl();

	@Override
	public Boolean addCategory(Category category) {
		Connection connection = null;
		Boolean flag = false;
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);//关闭事物自动提交
			flag = categoryDao.addCategory(connection, category);
			connection.commit();
		} catch (ClassNotFoundException | SQLException e) {
			if(connection!=null) {
				try {
					connection.rollback();//事物回滚
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}finally {
			JDBCUtils.close(connection);
		}
		return flag;
		
	}

	@Override
	public Boolean deleteCategory(Integer id) {
		Connection connection = null;
		Boolean flag = false;
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);//关闭事物自动提交
			flag = categoryDao.deleteCategory(connection, id);
			connection.commit();
		} catch (ClassNotFoundException | SQLException e) {
			if(connection!=null) {
				try {
					connection.rollback();//事物回滚
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}finally {
			JDBCUtils.close(connection);
		}
		return flag;
	}

	@Override
	public PageInfo getCategory(int pageNo, int pageSize, String categoryname) {
		Connection connection = null;
		PageInfo pageInfo = new PageInfo();
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);//关闭事物自动提交
			int offset = (pageNo-1)*pageSize;
			List<Category> category = categoryDao.getCategory(connection, offset, pageSize, categoryname);
			pageInfo.setCurrenPage(pageNo);
			pageInfo.setPageSize(pageSize);
			int categoryCount = categoryDao.getCategoryCount(connection);
			//通过总记录数求出总页数
			int pageCount = categoryCount;
			pageInfo.setPageCount(pageCount);
			boolean hasPre = pageNo<=1?false:true;
			pageInfo.setHasPre(hasPre);
			boolean hasNext = pageNo>=pageCount?false:true;
			pageInfo.setHasNext(hasNext);
			pageInfo.setPageData(category);
		} catch (ClassNotFoundException | SQLException e) {
			if(connection!=null) {
				try {
					connection.rollback();//事物回滚
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}finally {
			JDBCUtils.close(connection);
		}
		
		return pageInfo;
	}

}
